<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="代码生成列表"
      row-key="path"
      :indent="30"
      :request-api="getTableList"
      :columns="columns"
      :pagination="true"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="UploadFilled" @click="openDrawer()"> 导入 </el-button>
      </template>
      <!-- 菜单操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="previewDrawer(scope.row)"> 预览 </el-button>
        <!--        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>-->
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        <el-button type="primary" link :icon="Loading" @click="handleSyncDb(scope.row)"> 同步 </el-button>
        <el-button type="primary" link :icon="Download" @click="handlerGenTable(scope.row)"> 生成代码 </el-button>
      </template>
    </ProTable>
    <ImportTable ref="ImportTableRef" @success="proTable.getTableList()" />
    <PreviewCode ref="previewCodeRef" />
  </div>
</template>

<script setup lang="ts" name="codegenTable">
import { ref } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { Delete, View, UploadFilled, Download, Loading } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { loadPage, CodegenTable, deleteCodegen, syncCodegen, downLoadCodegen } from "@/api/system/codegenTable";
import ImportTable from "@/views/system/codeGenerator/ImportTable.vue";
import PreviewCode from "./PreviewCode.vue";
import { loadDatResourceList } from "@/api/system/dataResource";
import { useMessage } from "@/hooks/useMessage";

const message = useMessage();
const proTable = ref();
const ImportTableRef = ref<InstanceType<typeof ImportTable> | null>(null);
const previewCodeRef = ref<InstanceType<typeof PreviewCode> | null>(null);

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return loadPage(newParams);
};

const handleSyncDb = async (row: Partial<CodegenTable.ResCodegenTable> = {}) => {
  // 基于 DB 同步
  try {
    const tableName = row.tableName;
    await message.confirm("确认要强制同步" + tableName + "表结构吗?", "温馨提示");
    await syncCodegen(row?.id);
    message.success("同步成功");
  } catch (e) {}
};
/**
 * 删除按钮操作
 * @param id
 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm();
    await deleteCodegen(id);
    message.success("删除成功");
    proTable.value.getTableList();
  } catch (e) {}
};

const previewDrawer = (row: Partial<CodegenTable.ResCodegenTable> = {}) => {
  const params = {
    row: { ...row },
    getTableList: proTable.value?.getTableList
  };
  previewCodeRef.value?.acceptParams(params);
  console.log(row);
};
const handlerGenTable = async (row: CodegenTable.ResCodegenTable) => {
  const data = await downLoadCodegen(row.id);
  // 创建 blob
  const blob = new Blob([data], { type: "application/zip" });
  // 创建 href 超链接，点击进行下载
  window.URL = window.URL || window.webkitURL;
  const href = URL.createObjectURL(blob);
  const downA = document.createElement("a");
  downA.href = href;
  downA.download = "codegen-" + row.className + ".zip";
  downA.click();
  // 销毁超连接
  window.URL.revokeObjectURL(href);
};

const openDrawer = (row: Partial<CodegenTable.ResCodegenTable> = {}) => {
  const params = {
    row: { ...row },
    getTableList: proTable.value?.getTableList
  };
  ImportTableRef.value?.acceptParams(params);
};

// 表格配置项
const columns: ColumnProps[] = [
  { type: "sort", label: "排序", width: 80 },
  {
    prop: "dataSourceId",
    label: "数据源",
    align: "left",
    enum: () => loadDatResourceList(),
    fieldNames: { label: "name", value: "id" }
  },
  { prop: "tableName", label: "表名称" },
  { prop: "className", label: "实体" },
  { prop: "createBy", label: "创建人" },
  { prop: "createTime", label: "创建时间" },
  { prop: "updateBy", label: "更新人" },
  { prop: "updateTime", label: "更新时间" },
  { prop: "operation", label: "操作", width: 350, fixed: "right" }
];
</script>
